import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
import './index.scss'
import { Button, Card, Col, Form, Input, Row, Select, Space, Table, Tag, Tooltip } from "antd";
import type { InterviewEvaluation, InterviewEvaluationDto, InterviewEvaluationVo, OptionType } from "@/types";
import { getInterviewEvaluation } from "@/apis/interviewEvaluation";
import { useForm } from "antd/es/form/Form";
import { getInterviewOptions } from "@/apis/commonService";
import { filterOptionsByOptionGroupKey } from "@/utils/common";
import { EditOutlined } from "@ant-design/icons";

const InterviewEvaluation = forwardRef((props, ref) => {

    // 表格数据
    const [tableData,setTableData] = useState<InterviewEvaluation[]>([]);
    // 总记录数
    const [total,setTotal] = useState<number>(0);
    // 查询条件
    const [queryForm,setQueryForm] = useState<InterviewEvaluationDto>({
        current: 1,
        size: 6
    });
    // 查询表单标识
    const [form] = Form.useForm();
    // 页面选项
    const [evaluationStatusOptionList,setEvaluationStatusOptionList] = useState<OptionType[]>([]); // 评价状态选项
    const [evaluationResultOptionList,setEvaluationResultOptionList] = useState<OptionType[]>([]); // 评价结果选项

    const columns = [
        {
            title: '候选人',
            dataIndex: 'candidateName'
        },
        {
            title: '面试官',
            dataIndex: 'interviewerName'
        },
        {
            title: '评价状态',
            dataIndex: 'evaluationStatus',
            render: (value: number, record: InterviewEvaluationVo) => (
                <>
                    {
                        record.evaluationStatus === 0 ? 
                        <Tag color="default">未评价</Tag>
                        :
                        <Tag color="processing">已评价</Tag>
                    }
                </>
            )
        },
        {
            title: '评价结果',
            dataIndex: 'result',
            render: (value: number, record: InterviewEvaluationVo) => (
                <>
                    {
                        record.result === 0 ? 
                        <Tag color="warning">待定</Tag>
                        :
                        record.result === 1 ? 
                        <Tag color="success">通过</Tag>
                        :
                        <Tag color="error">不通过</Tag>
                    }
                </>
            )
        },
        {
            title: '评价内容',
            dataIndex: 'evaluationContent',
            width: 350,
            ellipsis: {
                showTitle: false
            },
            render: (evaluationContent: string, record: InterviewEvaluationVo) => (
                <Tooltip placement="topLeft" title={evaluationContent}>
                    {evaluationContent}
                </Tooltip>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, record: InterviewEvaluationVo) => (
            <Space size="middle">
                <Button onClick={() => doInterviewEvaluate(record)} type="primary" icon={<EditOutlined />}>评价</Button>
            </Space>
            ),
        },
    ];

    // 加载中标识
    const [loading, setLoading] = useState(false);
    // 当前选中的数据行id
    const [selectDataIds,setSelectDataIds] = useState<string[]>([]);
    // 当前选中的数据
    const [selectedDatas,setSelectDatas] = useState<InterviewEvaluationVo[]>([]);
    
    /** 表格选中回调  */
    const tabSelectChange = (selectedRowKeys: React.Key[], selectedRows: InterviewEvaluationVo[]) => {
        setSelectDataIds(selectedRowKeys as string[]);
        setSelectDatas(selectedRows as InterviewEvaluationVo[]);
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    }

    /** 改变查询条件  */
    const changeSeleteCondition = (params: InterviewEvaluationDto) => {
        setQueryForm(params);
    }

    /** 查询  */
    const queryTableData = async () => {
        try {
            setLoading(true);            
            const res = await getInterviewEvaluation(queryForm);
            console.log("查询结果Res====>",res);
            // 若当前查询的记录数为0 且当前页数不为1 则当前页数减少1页后重新查询
            if (res.data.records.length === 0 && queryForm.current != 1) {
                setQueryForm({
                    ...queryForm,
                    current: queryForm.current - 1
                })
            }
            setTableData(res.data.records);
            setTotal(res.data.total);
        } catch (error) {
            console.log(error);
        }finally{
            setLoading(false);
        }
    }

    /** 面试评价  */
    const doInterviewEvaluate = (val: InterviewEvaluationVo) => {
        console.log("评价数据====>",val);
    }

    /** 初始化面试选项 */
    const InitOptions = async () => {
        const optionGroupKeys: string[] = ['interviewEvaluationStatus','interviewEvaluationResult'];
        const res = await getInterviewOptions(optionGroupKeys);
        const allOptions: OptionType[] = res.data.data;
        setEvaluationStatusOptionList(filterOptionsByOptionGroupKey(allOptions,'interviewEvaluationStatus'));
        setEvaluationResultOptionList(filterOptionsByOptionGroupKey(allOptions,'interviewEvaluationResult'));
    }

    /** 页面初始化 或 查询条件发生改变时 调用查询 */
    useEffect(() => {
        queryTableData();
    },[queryForm])

    useEffect(() => {
        InitOptions();
    },[]);
    
    return (
        <div className="interview-evaluation">
            <Card className="card" title="查询条件">
                <Form
                    form={form}
                    layout="inline"
                    name="interview-evaluation"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ width: '100%' }}
                    initialValues={{ }}
                    onFinish={(val) => changeSeleteCondition({...queryForm,...val})}
                    autoComplete="off"
                >
                    <Row style={{ width: '100%' }}>
                        <Form.Item<InterviewEvaluationDto>
                            label="候选人"
                            name="candidateName"
                        >
                            <Input placeholder="请输入候选人名称"/>
                        
                        </Form.Item>
                        
                        <Form.Item<InterviewEvaluationDto>
                            label="面试官"
                            name="interviewerName"
                        >
                            <Input placeholder="请输入面试官名称"/>
                        </Form.Item>

                        <Form.Item<InterviewEvaluationDto>
                            label="评价状态"
                            name="evaluationStatus"
                        >
                            <Select
                                placeholder="请选择"
                                allowClear
                                style={{ width: 200 }}
                                options={evaluationStatusOptionList}
                            />
                        </Form.Item>

                        <Form.Item<InterviewEvaluationDto>
                            label="评价结果"
                            name="result"
                        >
                            <Select
                                placeholder="请选择"
                                allowClear
                                style={{ width: 200 }}
                                options={evaluationResultOptionList}
                            />
                        </Form.Item>
                    </Row>

                    <Row justify='end' style={{ width: '100%',marginTop: '20px' }}>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Row>
                </Form>
            </Card>

            <Card className="card" title="查询结果">
                <Table
                    rowKey="id"
                    loading={loading} 
                    dataSource={tableData} 
                    columns={columns}
                    rowSelection={{ type: 'checkbox',onChange: tabSelectChange,selectedRowKeys: selectDataIds,preserveSelectedRowKeys: true }}
                    pagination={{
                        showQuickJumper: true,
                        total: total,
                        showTotal: (total) => `共 ${total} 条数据`,
                        current: queryForm.current,
                        pageSize: queryForm.size,
                        showSizeChanger: true,
                        onChange: (current,size) => changeSeleteCondition({...form.getFieldsValue(),current,size}),
                        pageSizeOptions: [6,10,20,50,100]
                    }}  
                />
            </Card>
        </div>
    )

    useImperativeHandle(ref, () => ({
    }));
});

export default InterviewEvaluation;